package com.chocus.core.service.product;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.chocus.core.bean.product.Brand;
import com.chocus.core.bean.product.BrandQuery;
import com.chocus.core.dao.product.BrandDao;

import cn.itcast.common.page.Pagination;
import redis.clients.jedis.Jedis;

/**
 * 品牌实现类
 * 
 * @author Administrator
 *
 */
@Service("brandService")
public class BrandServiceImpl implements BrandService {

	@Autowired
	private BrandDao brandDao;

	@Autowired
	@Qualifier("jedis")
	private Jedis jedis;

	/**
	 * 通过查询返回品牌列表
	 * 
	 * @param brandQuery
	 * @return
	 */
	@Override
	public Pagination getBrandByQuery(String name, Integer isDisplay, Integer pageNo) {

		// 拼接分页参数
		StringBuilder params = new StringBuilder();
		BrandQuery brandQuery = new BrandQuery();
		if (name != null) {
			brandQuery.setName(name);
			params.append("name=").append(name);
		}

		if (isDisplay != null) {
			brandQuery.setIsDisplay(isDisplay);
			params.append("&isDisplay=").append(isDisplay);
		} else {
			brandQuery.setIsDisplay(1);
			params.append("&isDisplay=").append(1);
		}
		// 当前页 pageNo如果是null 或小于1时 设置pageNo =1
		brandQuery.setPageNo(Pagination.cpn(pageNo));
		// 设置每页条数
		brandQuery.setPageSize(3);
		// 构建分页对象 （当前页，每页数（自定义）、总条数）
		Pagination pagination = new Pagination(brandQuery.getPageNo(), brandQuery.getPageSize(),
				brandDao.getBrandCountByQuery(brandQuery));
		// 存放数据
		pagination.setList(brandDao.getBrandByQuery(brandQuery));
		// 设置分页信息
		String url = "/brand/list.do";

		pagination.pageView(url, params.toString());

		return pagination;
	}

	/**
	 * 通过id查询返回品牌
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Brand getBrandById(long id) {
		return brandDao.getBrandById(id);
	}

	/**
	 * 修改 品牌，并保存品牌到redis数据库
	 */
	@Override
	public int update(Brand brand) {
		// TODO Auto-generated method stub
		int count = brandDao.update(brand);
		jedis.hset("brand2", String.valueOf(brand.getId()), brand.getName());
		return count;
	}

	/**
	 * 删除
	 */
	@Override
	public int deletes(Long[] ids) {
		// TODO Auto-generated method stub
		return brandDao.deletes(ids);
	}

	/**
	 * 查询品牌列表
	 * 
	 * @param brandQuery
	 * @return
	 */
	public List<Brand> getBrandListByQuery() {
		BrandQuery brandQuery = new BrandQuery();
		brandQuery.setIsDisplay(1);
		return brandDao.getBrandByQuery(brandQuery);
	}
}
